﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Spider
{
    class RequestByWebBroswer:IRequest
    {
        WebBrowser browser;

        public RequestByWebBroswer()
        {
            if (browser == null)
                browser = new WebBrowser();
        }

        ~ RequestByWebBroswer()
        {
            if (browser != null)
            {
                browser.Dispose();
                browser = null;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if(browser!=null)
            {
                browser.Dispose();
                browser = null;
            }
        }

        #endregion
        #region Variable
        delegate void NavigateHandle(Uri uri);
        #endregion

        #region IRequest Members
        private void navigate(Uri uri)
        {
            browser.Navigate(uri);
        }

        private void invokeNavigate(Uri uri)
        {
            browser.BeginInvoke(new NavigateHandle(navigate), new object[] { uri });
        }

        public PageClass GetPage(Uri uri)
        {
            PageClass page = new PageClass();

            invokeNavigate(uri);

            while (!(browser.ReadyState ==WebBrowserReadyState.Complete))
            {
                Thread.Sleep(100);
            }
            page.URL = uri;
            page.html = browser.DocumentText;

            return page;
        }

        public Uri GetJSUri(string htmlElement)
        {
            HtmlElementCollection elementColl = browser.Document.Links;

            foreach (HtmlElement element in elementColl)
            {
                if (element.TagName.Equals("A") || element.TagName.Equals("Img"))
                {
                    if (element.InnerHtml.Equals(htmlElement.ToString()))
                        element.InvokeMember("Click");
                }
            }

            return browser.Url;
        }
        #endregion

        #region Method
        private void initControl()
        {
            browser = new WebBrowser();
            browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
        }

        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            throw new NotImplementedException();
        }
        #endregion

    }
}
